#include <stdio.h>

#include <stdlib.h>
#include <mysql.h>

#include <errno.h>

#define DB_HOST "10.19.141.104"
#define DB_USER "root"
#define DB_PASS "Bocom_123"
#define DB_NAME "enc_account_database"

#include "uthash.h"

//public.spring.datasource.url.host=10.19.141.104:3306
//public.spring.datasource.username.host=root
//public.spring.datasource.password.host=Bocom_123

MYSQL *connect_to_mysql() {
    MYSQL *conn = mysql_init(NULL);
    if (conn == NULL) {
        fprintf(stderr, "mysql_init() failed\n");
        return NULL;
    }

    if (mysql_real_connect(conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, 3306, NULL, 0) == NULL) {
        fprintf(stderr, "mysql_real_connect() failed: %s\n", mysql_error(conn));
        mysql_close(conn);
        return NULL;
    }

    int r = mysql_options(conn, MYSQL_SET_CHARSET_NAME, "utf8");
    if (r == 0) {
        printf("设置字符集 utf8 ok\n");
    }

    return conn;
}


void query_database(MYSQL *conn, const char *query) {

    mysql_query(conn,"set names 'utf8';");

    if (mysql_query(conn, query)) {
        printf("Line %d in function %s mysql_query() failed: %s\n", __LINE__, __FUNCTION__, mysql_error(conn));
        return;
    }

    MYSQL_RES *result = mysql_store_result(conn);
    if (result == NULL) {
        fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(conn));
        return;
    }

    unsigned int num_fields = mysql_num_fields(result);
    MYSQL_ROW row;

    while ((row = mysql_fetch_row(result))) {
        for (int i = 0; i < num_fields; i++) {
            printf("%s ", row[i] ? row[i] : "NULL");
        }
        printf("\n");
    }

    mysql_free_result(result);
}

extern int errno;

int main() {

    int errnum;

    errnum = errno;

    fprintf(stderr, "错误号: %d\n", errno);
    perror("通过 perror 输出错误\n");
    fprintf(stderr, "打开文件错误: %s\n", strerror( errnum ));

    printf("start \n");

    char *poem = "开始\n";

    printf(poem);

    MYSQL mysql;
    //初始化
    mysql_init(&mysql);

    MYSQL *conn = connect_to_mysql();
    if (conn == NULL) {
        fprintf(stderr, "Connection to MySQL failed.\n");
        return 1;
    }

    const char *query = "SELECT * FROM sys_loc_city";
    query_database(conn, query);

    const char *query1 = "SELECT * FROM sys_loc_district";
    query_database(conn, query1);

    mysql_close(conn);
    return 0;
}
